package com.example.springbootdemo.util;

import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Author: ShengXiaJia
 * @Date: 2019/12/6 13:59
 * @Description: 文件file上传工具类
 */
public class FileUtil {


    public static void main(String[] args) throws Exception {
        //读取图片
        BufferedInputStream in = new BufferedInputStream(new FileInputStream("C:\\Users\\HZYL\\Desktop\\2.jpeg"));
        //字节流转图片对象
        Image bi = ImageIO.read(in);
        //获取图像的高度，宽度
        int height = bi.getHeight(null);
        int width = bi.getWidth(null);
        //构建图片流
        BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //绘制改变尺寸后的图
        tag.getGraphics().drawImage(bi, 0, 0, width, height, null);
        //输出流
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("C:\\Users\\HZYL\\Desktop\\5.png"));
        //JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        //encoder.encode(tag);
        ImageIO.write(tag, "PNG", out);
        in.close();
        out.close();
        //转字节流
        //ByteArrayOutputStream out = new ByteArrayOutputStream();

        //ImageIO.write(tag, "PNG",out);

        //InputStream is = new ByteArrayInputStream(out.toByteArray());
    }

    /**
     * 根据指定大小压缩图片
     */
    public static byte[] compressPicForScale(FileInputStream in, long desFileSize) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
        while (-1 != (n = in.read(buffer))) {
            output.write(buffer, 0, n);
        }
        byte[] imageBytes = output.toByteArray();

        if (imageBytes == null || imageBytes.length <= 0 || imageBytes.length < desFileSize * 1024) {
            return imageBytes;
        }
        long srcSize = imageBytes.length;
        double accuracy = getAccuracy(srcSize / 1024);
        try {
            while (imageBytes.length > desFileSize * 1024) {
                ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);
                Thumbnails.of(inputStream)
                        .scale(accuracy)
                        .outputQuality(accuracy)
                        .toOutputStream(outputStream);
                imageBytes = outputStream.toByteArray();
            }
        } catch (Exception e) {
        }
        return imageBytes;
    }

    /**
     * 自动调节精度(经验数值)
     *
     * @param size 源图片大小
     * @return 图片压缩质量比
     */
    private static double getAccuracy(long size) {
        double accuracy;
        if (size < 900) {
            accuracy = 0.85;
        } else if (size < 2047) {
            accuracy = 0.6;
        } else if (size < 3275) {
            accuracy = 0.44;
        } else {
            accuracy = 0.4;
        }
        return accuracy;
    }


    /**
     * 根据传入的长宽压缩图片尺寸
     */
    public static InputStream changeImgSize(Integer height, Integer width, FileInputStream fileInputStream) throws Exception {
        //读取图片
        BufferedInputStream in = new BufferedInputStream(fileInputStream);
        //字节流转图片对象
        Image bi = ImageIO.read(in);
        //构建图片流
        BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //绘制改变尺寸后的图
        tag.getGraphics().drawImage(bi, 0, 0, width, height, null);
        //转字节流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(tag, "PNG", out);
        InputStream is = new ByteArrayInputStream(out.toByteArray());
        in.close();
        out.close();
        return is;
    }

    /**
     * 根据UUID给file文件随机命名
     */
    public static String getRandomName(MultipartFile logoFile) {
        String OriginalName = logoFile.getOriginalFilename();
        String suffixName = OriginalName.substring(OriginalName.lastIndexOf("."), OriginalName.length());
        return UUID.randomUUID().toString().replace("-", "") + suffixName;
    }

    /**
     * 根据file文件返回后缀名
     */
    public static String getSuffixName(MultipartFile logoFile) {
        String OriginalName = logoFile.getOriginalFilename();
        String suffixName = OriginalName.substring(OriginalName.lastIndexOf("."), OriginalName.length());
        return suffixName;
    }


    /**
     * 根据UUID给file文件随机命名,且返回后缀名
     */
    public static List<String> getRandomNameAndSuf(MultipartFile logoFile) {
        String OriginalName = logoFile.getOriginalFilename();
        String suffixName = OriginalName.substring(OriginalName.lastIndexOf("."), OriginalName.length());
        String name = UUID.randomUUID().toString().replace("-", "") + suffixName;
        List<String> list = new ArrayList<>();
        list.add(name);
        list.add(suffixName);
        return list;
    }

}
